<?php

namespace Home\Controller;

class UsersController extends CommonController {

    public function login() {
        $UserService = D('User', 'Service');

        $user = json_decode($_POST['req'], true);
        $result = $UserService->login($user);
        if (false === $result['status']) {
            return $this->ajaxReturn($result['data']['error']);
        }

        $result['sid'] = $_SESSION['sid'];
        $result['data'] = $_SESSION['user'];

        return $this->ajaxReturn($result);
    }

    public function logout() {
        D('User', 'Service')->logout();

        return $this->ajaxReturn($this->buildResult(true, '用户登出成功'));
    }

    public function create() {
        if (!isset($_POST['req'])) {
            return $this->ajaxReturn($this->buildResult(false, 'req必填'));
        }

        $User = D('User');
        $user = json_decode($_POST['req'], true);
        $user['password'] = md5($user['password']);

        $result = upload(C('UPLOAD_ROOT') . 'user/');
        if (false == $result['status']) {
            return $this->ajaxReturn($this->buildResult(false, '头像保存失败'));
        }
        $user['img'] = $result['info'][0]['path'];

        if ($user = $User->create($user)) {
            if (flase === $User->add($user)) {
                return $this->ajaxReturn($this->buildResult(false, $User->getDbError()));
            }
        }

        return $this->ajaxReturn($this->buildResult(true, '注册成功'));
    }

    public function update() {
        if (!isset($_POST['req'])) {
            return $this->ajaxReturn($this->buildResult(false, 'req必填'));
        }

        $User = D('User');
        $user = json_decode($_POST['req'], true);
        if (isset($user['password'])) {
            $user['password'] = md5($user['password']);
        }

        $result = upload(C('UPLOAD_ROOT') . 'user/');
        if (false != $result['status']) {
            $user['img'] = $result['info'][0]['path'];
        }

        if ($user = $User->create($user)) {
            if (flase === $User->save($user)) {
                return $this->ajaxReturn($this->buildResult(false, $User->getDbError()));
            }
        }

        return $this->ajaxReturn($this->buildResult(true, '更新用户信息成功'));
    }

    public function test() {
        $this->display();
    }
}
